package org.springframework.samples.webflow.dao;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.webflow.dto.Person;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;



@Component
public class PersonDAO  {

	private static final Logger logger = LoggerFactory
			.getLogger(PersonDAO.class);

	@Autowired
	private SessionFactory sessionFactory;

	@Autowired
	public CacheManager cacheManager;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Transactional
	public Person  getPersonById(long id){
		logger.info("getPersonById called");
		Person p = null;
		
		Cache cache=cacheManager.getCache("person");
		if(cache != null){
			Element e = cache.get(id);
			if(e != null){
				p = (Person)e.getObjectValue();
			}
		}
		if(p == null){ 
			p = (Person) sessionFactory.getCurrentSession().load(Person.class, id);//getHibernateTemplate().load(Person.class, id);
			savePersonCache(p);
		}
		return p;
	}

	
	public void savePersonCache(Person p) {
		Cache cache = cacheManager.getCache("person");
		cache.put(new Element(p.getId(), p));
	}

}
